/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */

/**
 * @param {TreeNode} root
 * @return {number}
 */
export var minCameraCover = function (root) {
  let ans = 0
  const dfs = node => {
    // 0: 未监控，1: 摄像头， 2，已监控
    if (!node) return 2
    const left = dfs(node.left)
    const right = dfs(node.right)
    if (left === 2 && right === 2) return 0
    // 如果左右节点有一个未被监控，则当前节点安装摄像头
    if (left === 0 || right === 0) {
      ans++
      return 1
    }
    // 左边或右边有一个摄象头，说明当前节点已被监控
    if (left === 1 || right === 1) return 2
    // 余下的就是当前节点未被监控状态
    return 0
  }
  // 根节点未监控，则安装摄像头
  return dfs(root) === 0 ? ++ans : ans
}
